const crypto = require('crypto');

class CryptoHelper {
    constructor(secretKey) {
        this.algorithm = 'aes-256-cbc';
        this.key = crypto.scryptSync(secretKey, 'salt', 32);
    }
   // aes-256-cbc 加密
    encrypt(text) {
        const iv = crypto.randomBytes(16);
        const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
        let encrypted = cipher.update(text, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        return iv.toString('hex') + ':' + encrypted;
    }

    // aes-256-cbc 解密
    decrypt(encryptedData) {
        const parts = encryptedData.split(':');
        const iv = Buffer.from(parts[0], 'hex');
        const encrypted = parts[1];
        const decipher = crypto.createDecipheriv(this.algorithm, this.key, iv);
        let decrypted = decipher.update(encrypted, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    }

    // hash 加密
    hash(text) {
        return crypto.createHash('sha256').update(text).digest('hex');
    }
    

}

// 创建预配置的实例
const cryptoHelper = new CryptoHelper('crm');

module.exports = {
    CryptoHelper,
    cryptoHelper  // 预配置的实例
};